﻿using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Diagnostics;

namespace AutoCADDotNetLibrary.Analyzers.Analyzers
{
    [DiagnosticAnalyzer(LanguageNames.CSharp)]
    public class IExtensionApplicationAnalyzer : DiagnosticAnalyzer
    {
        public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(ACDiagnostic.Rule_IExtensionApplicationOnlyOne);

        public override void Initialize(AnalysisContext context)
        {
            context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None);
            context.EnableConcurrentExecution();
            context.RegisterCompilationStartAction(compilationStartAnalysisContext =>
            {
                if (!Helper.GetEnableAutoCADAnalyzers(compilationStartAnalysisContext.Options))
                    return;

                List<INamedTypeSymbol> typeList = new List<INamedTypeSymbol>();
                compilationStartAnalysisContext.RegisterSymbolAction(symbolAnalysisContext =>
                {
                    INamedTypeSymbol namedTypeSymbol = symbolAnalysisContext.Symbol as INamedTypeSymbol;
                    if (namedTypeSymbol.AllInterfaces.FirstOrDefault(x => x.ToDisplayString() == "Autodesk.AutoCAD.Runtime.IExtensionApplication") == null)
                        return;

                    lock (typeList)
                    {
                        typeList.Add(namedTypeSymbol);
                    }
                }, SymbolKind.NamedType);

                compilationStartAnalysisContext.RegisterCompilationEndAction(symbolAnalysisContext =>
                {
                    if (typeList.Count > 1)
                    {
                        typeList.ForEach(x =>
                        {
                            symbolAnalysisContext.ReportDiagnostic(Diagnostic.Create(ACDiagnostic.Rule_IExtensionApplicationOnlyOne, x.Locations.FirstOrDefault(), x.ToDisplayString()));
                        });
                    }
                });
            });
        }
    }
}
